using System;
using System.Reflection;
using Sirenix.OdinInspector.Editor;
using Sirenix.Utilities.Editor;
using UnityEngine;
using Sirenix.OdinInspector.Editor.Drawers;
using Sirenix.Utilities;

namespace BTEditor
{
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method)]
    public class ColorIfAttribute : Attribute
    {
        public string MemberName;
        public Color Color;
        public object Value;

        public ColorIfAttribute(string memberName, object value, float r, float g, float b, float a = 1f)
        {
            MemberName = memberName;
            Value = value;
            Color = new Color(r, g, b, a);
        }
    }

    [DrawerPriority(1, 0, 0)]
    public class ColorIfAttributeDraws : OdinAttributeDrawer<ColorIfAttribute>
    {
        /// <summary>
        /// Draws the property.
        /// </summary>
        protected override void DrawPropertyLayout(GUIContent label)
        {
            bool result;
            string errorMessage;

            var property = this.Property;
            var attribute = this.Attribute;

            OdinUtil.HandleIfAttributesCondition(this, property, attribute.MemberName, attribute.Value, out result,
                out errorMessage);

            if (errorMessage != null)
            {
                SirenixEditorGUI.ErrorMessageBox(errorMessage);
                this.CallNextDrawer(label);
            }
            else
            {
                if (result)
                {
                    GUIHelper.PushColor(attribute.Color);
                }

                this.CallNextDrawer(label);

                if (result)
                {
                    GUIHelper.PopColor();
                }
            }
        }
    }
}